<template>
	<view>
		<view style="width:100%;height:auto;position:relative">
		   <!-- <view class="search-input">
				<icon type="search" size="15" style="padding-top:15rpx"/>
				<input class="search" @confirm="searchData" type="text" v-model="dname" confirm-type="search" placeholder="请输入商品或店铺名" />
				<icon type="clear" size="15" @click="clearSearch" style="padding-top:15rpx;flex:1;text-align: right;"/>
			</view> -->
			<!-- #ifdef MP-WEIXIN -->
				<view class="orderwarp" style="top:0upx">
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
				<view class="orderwarp" style="top:80upx">
			<!-- #endif -->
				<u-tabs v-model="active" :current="active" lineWidth="100" lineColor="#F66B71" :scrollable="false" :list="orderTabs" @click="onChange"></u-tabs>
			</view>
			<view style="margin-top:100rpx;">
				<view v-if="nodata"> 
					<u-empty
						mode="order"
						:icon="no_data"
					>
					</u-empty>
				</view>
				<view v-else class="cont">
					<block v-for="(item,index) in goodsData" :v-key="index">
						<view style="background-color:#ffffff;margin:20rpx 0rpx;padding:20rpx">
							<view style="display: flex;justify-content: space-between;padding-top:10rpx">
								<view style="display: flex;">
									<image :src="dclogo" mode="widthFix" style="width:100upx;height:100upx"></image>
									<view style="margin-left:10upx">{{item.restUserShop.shopName}}</view>
								</view>
								<view v-if="item.ostate=='3'">已退款</view>
								<view v-if="item.ostate=='1'">已支付</view>
								<view v-if="item.ostate=='2'">已完成</view>
								<view v-if="item.ostate=='0'">待支付</view>
							</view>
							<view v-for="child in item.disheorderOrderitems">
								<view @click="goDetail(item,child)">
									<view style="display:flex;margin-top:20upx">
										<image v-if="child.dimg" mode="aspectFill" style="width:200upx;height:200upx;border-radius: 20rpx;"  :src="uploadFilePath+child.dimg"></image>
										<image v-else mode="aspectFill" style="width:200upx;height:200upx;"  :src="default_img"></image>
										<view style="width:68%;margin-left:20upx">
											<view style="display:flex;justify-content: space-between;">
												<view style="line-height: 1.5rem;">
													<view style="font-size:1rem;font-weight: bold;">{{child.dishesName}}</view>
													<view style="font-size:1rem">取餐码：<text>{{item.qcode}}</text></view>
													<view style="font-size:1rem;color:#666">{{item.createTime}}</view>
												</view>
												<view style="line-height: 1.5rem;">
													<view style="font-size:1rem;font-weight: bold;">￥{{child.idisPrice}}</view>
													<view style="font-size:1rem">共{{child.buyNum}}件</view>
												</view>
											</view>
											<view>备注：{{child.memo}}</view>
										</view>
									</view>
								</view>
								<view style="display:flex;margin:10px;">
									<u-button :plain="true" v-if="item.ostate==2" text="评价" size="small" style="width:30%" @click="goEvaluate(child)"></u-button>
									<u-button type="success" v-if="item.ostate==2 && active==0" :plain="true" :hairline="true" size="small" style="width:30%" text="再来一单" @click="goDetailDc(child)"></u-button>
								</view>
							</view>
							<view style="display:flex" v-if="item.ostate==0">
								<u-button type="success" :plain="true" :hairline="true" size="mini" customStyle="width:30%" text="去支付" @click="continuePay(item)"></u-button>
								<u-button :plain="true" :hairline="true"  :customStyle="cusCssbtn" size="mini" text="取消订单" @click="removeOrder(item)"></u-button>
							</view>
						</view>
					</block>
				</view>
			</view>
		</view>
		<u-modal :show="show" :title="title" :content='content'></u-modal>
		<u-popup :show="showkw" mode="center"  @close="onClose" @open="onOpen">
			<view style="width:96%;height:70%;margin:0rpx auto;border:1px solid #f3f3f6">
				<u--textarea
				    style="width:100%"
					maxlength="100"
					autoHeight 
					v-model="memo"
					placeholder="请输入退单原因"
					@confirm="onChangeMemo"
				  ></u--textarea>
			</view>
			<view style="width:40%;margin-top:20rpx;position:relative;float:right">
			  <u-button @click="onClose" size="small">取消</u-button>
			  <u-button @click="applyRecokeHandle" color="#F66B71" size="small" style="margin-left:20rpx">确定</u-button>
			</view>
		</u-popup>
		<u-popup :show="showPay" mode="bottom" :round="10" @close="closePay">
			<view style="padding:10px;">
				<view style="text-align: center;">
					实付金额
				</view>
				<view style="text-align: center;font-size:1.2rem">￥{{sumMony}}</view>
				<view style="margin:10px 0px">选择支付方式:</view>
				<view>
					<radio-group @change="radioChange">
						<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in payWayxcx" :key="item.value">
							<view style="display:flex;justify-items: center;">
								<img :src="item.imgurl" style="width:60upx;height:60upx"/>
								<view style="line-height:60upx;height:60upx;padding-left:5px">{{item.label}}</view>
							</view>
							<view>
								<radio :value="item.value" :checked="item.state" />
							</view>
						</label>
					</radio-group>					
					<u-button type="success" size="large" @click="goPay">立即支付</u-button>										
				</view>
			</view>
		</u-popup>
		<u-modal :show="delState" :title="dtitle" @confirm="sureRemoveOrder" @cancel="closeMd" :content='content' showConfirmButton showCancelButton></u-modal>
		<u-modal :show="showtd" :title="tdtitle" :content="tdcontent" showConfirmButton showCancelButton :zoom="false" @confirm="goTuidan" @cancel="closeTdModel"></u-modal>
	</view>
</template>

<script>
	import Config from '@/util/index.js'
	import {
		orderList,dpjOrder,cardxcxPay,redayxcxPay,orderRemove
	} from '@/api/cart'
	import {
	 getwxOpenId
	} from '@/api/user'
	export default {
		data() {
		    return {
				active:0,
			    time: 30 * 60 * 60 * 1000,
			    tdtag:1,
				tdtitle:"退单提醒",
				tdcontent:"你确定要退单吗?不再考虑一下?",
				dtitle:'取消订单',
				content:'是否确认取消订单？',
			    moreData:false,
			    nodata:false,
				showtd:false,
				delState:false,
			    goodsData:[],
			    pageNum:0,
			    pageSize:10,
			    total:0,
				cusCssbtn:{
					width:"30%"
				},
				dclogo:'',
				no_data:'',
				sumMony:0,
				orderId:'',
				showPay:false,
				payWayxcx:[
					{
					  imgurl:"../../../../static/images/wxlog.jpeg",
					  value:'0',
					  label:'微信支付',
					  state:true
					},
					{
					  imgurl:"../../../../static/images/cardlog.png",
					  value:'1',
					  label:'卡支付',
					  state:false
					}
				],
				orderTabs:[
					{
						name: '全部',
					},
					{
						name: '待评价'
					},
					{
						name: '售后订单'
					}
				],
			    showkw:false,
			    memo:'',
				default_img:'',
				scode:'',
				rcode:'',
				payWaytype:0,
				tdorderid:'',
				userId:'',
			    state:"",
			    tdorder:'',
			    tdstate:'',
			    uploadFilePath:'',
				show:false,
				title:'确认退单',
				content:'你确定要退单吗，不再考虑一下？'
		    }
		},
		filters:{
			OState(type){
				switch(parseInt(type)){
					 case 0:
					  return "已下单"
					  break;
					case 1:
					  return "已接单"
					  break;
					case 2:
					  return "已完成"
					  break;
					case 3:
					  return "已退单"
					  break;
					default:
					  return ""
				}
			}
		},
	   /**
	   * 生命周期函数--监听页面加载
	   */
	    onLoad(options) {
			let _this = this
			uni.getStorage({
				key: 'deptdas',
				success: function (res) {
					let depts = JSON.parse(res.data)
					_this.scode = depts.scode
					_this.rcode = depts.rcode	
					_this.onChange()
				}
			})
			this.uploadFilePath = Config.get('apiUrl')
	    },
		
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function () {
		  this.queryOrderBystate()
		},
		created(){
			this.userId = uni.getStorageSync('userId')
			this.no_data = this.picUrl + "no_data.jpg"
			this.dclogo = this.picUrl + "dclogo.png"
			this.default_img = this.picUrl + "goods.png"
		},
		methods:{
			closeTdModel(){
				this.showtd = false
			},
			sureRemoveOrder(){
				orderRemove(this.orderId).catch(res => {
					if(res.data.code == 200){
						uni.showToast({
						  title:"取消成功",
						  icon: 'none',
						  duration: 2000
						});
						this.goodsData = []
						this.delState = false
						this.showPay = false
						this.pageNum = 0
						this.moreData=false
						this.nodata=false
						this.queryOrderBystate()
					}
				})
			},
			closeMd(){
				this.delState = false
				uni.showToast({
					title:"已取消",
					icon: 'none',
					duration: 2000
				});
			},
			removeOrder(row){
				this.orderId = row.orderId
				this.delState = true
			},
			closePay(){
				this.showPay = false
			},
			radioChange(val){
				this.payWaytype = val.detail.value
			},
			getOpenid(cdos){
				let params = {
					code:cdos,
					userId:this.userId
				}
				let _this = this
				getwxOpenId(params).catch(resp=>{
					let pars = {
						orderNumber:this.orderId,
						openId:resp.data.openid
					}
					redayxcxPay(pars).catch(resp=>{
						  //调用微信官方支付接口弹出付款界面,输入密码扣款
						wx.requestPayment({
						     timeStamp:resp.data.timeStamp,  //时间戳
						     nonceStr:resp.data.nonceStr,   //随机字符串
						     package:resp.data.package,    //prepay_id
						     signType:resp.data.signType,   //签名算法MD5
						     paySign:resp.data.paySign,    //签名
						     success (res) {
						       if (res.errMsg == "requestPayment:ok"){
								  uni.showToast({
								    title:"支付成功",
								    icon: 'none',
								    duration: 2000
								  });
								  _this.goodsData = []
								  _this.showPay = false
								  _this.pageNum = 0
								  _this.moreData=false
								  _this.nodata=false
								  _this.queryOrderBystate()
						       }else{
								  uni.showToast({
								    title:"支付失败",
								    icon: 'none',
								    duration: 2000
								  });
						       }
						     },
						     fail (res) { 
							   uni.showToast({
							     title:"已取消支付",
							     icon: 'none',
							     duration: 2000
							   });
							    _this.showPay = false
							   //取消支付，购物车里的商品不做删除
							   // _this.getAllCart()
						     }
						})
					})
				})
			},
			continuePay(data){
				this.orderId = data.orderId
				this.sumMony = data.paymoney
				this.showPay = true
			},
			goPay(){
				if(this.payWaytype==1){
				  //卡支付
				  let psx = {
					userId:this.userId,
					orderId:this.orderId
				  }
				  cardxcxPay(psx).catch(respz=>{	
					if(respz.data.code==200){
						this.goodsData = []
						this.showPay = false
						this.pageNum = 0
						this.moreData=false
						this.nodata=false
						this.queryOrderBystate()
					}
				  })
				}else{
					let _this = this
					uni.login({
					  	provider: 'weixin',
					  	success: res => {
					  		if (res.code) {
					  			// 获取到登录凭证code
					  			let code = res.code;
					  			// 调用后端接口，传递code进行获取openid操作
								_this.getOpenid(code)  
					  		}
					  	}
					});
				}
			},
			goEvaluate(row){
				let params = JSON.stringify(row)
				uni.navigateTo({
					url:`../../evaluate/index?parsData=${params}`
				})
			},
			goDetailDc(row){
				let params = JSON.stringify(row)
				uni.redirectTo({
					url:`../../goods/detail?gid=${row.dishesId}`
				})
			},
			goDetail(pda,cda){
				let obj = {
					shopName:pda.restUserShop.shopName,
					dimg:cda.dimg,
					ostate:pda.ostate,
					paymoney:pda.paymoney,
					state:'支付成功',
					createTime:pda.createTime,
					dishesName:cda.dishesName,
					speName:cda.speName,
					company:'启真餐饮',
					payway:pda.payType,
					payorder:pda.payNo,
					orderId:pda.orderId
				}
				let params = JSON.stringify(obj)
				uni.setStorageSync('tabActive', this.active);
				uni.navigateTo({
					url:`detail?parsData=${params}`
				})
			},
			searchData(){
				this.goodsData = []
				this.pageNum = 0
				this.queryOrderBystate(this.dname,this.pagenum,this.pagesize);
			},
			onOpen(){},
			getGoodsDetail(orderId,orderstate){
			    let params = {
			      oid:orderId
			    }
			    let _this = this
			    Api.queryGoodsDetail(params).then(res=> {
			      if(res.retCode == 0){
			        if(res.orderinfo.state == "5"){
			          uni.showToast({
			            title:"商家已做好，不能退单",
			            icon: 'none',
			            duration: 2000
			          });
			        }else{
						_this.tdorderid = orderId
						_this.tdstate = orderstate
			           _this.onTuidan()
			        }
			      }
			    })
			  },
			  onClose(){
			    this.showkw=false
			  },
			  queryOrderBystate(){
			    // this.pagenum=-1
			    if(this.moreData){
			      return false
			    }else{
			      this.pageNum++
			    }
			    uni.showLoading({
			      title: '加载中...',
			    })
			    let userId = uni.getStorageSync('userId')
			    let params = {
			      userId:userId,
			      ostate:this.state,
				  deptId:this.rcode,
			      pageNum:this.pageNum,
			      pageSize:this.pageSize
			    }
			    let _this = this
			    orderList(params).catch(res=>{
			        if(res.data.rows.length > 0){
						const newList = res.data.rows
						const total = res.data.total
						if(_this.goodsData.length < total){
						  _this.goodsData=[..._this.goodsData,...newList]
						}else{
						  _this.moreData=true
						}
			        }else{
						if(_this.pageNum==1){
							console.log("test1121")
						  _this.nodata=true
						 }
						 _this.moreData=true
			        }
					uni.hideLoading()
			    })
			  },
			  onChangeMemo(val){
			    this.memo =val
			  },
			  //退单申请
			  applyRecokeHandle(){
			     //校验表单
			     if(this.memo==""){
			      uni.showToast({
			        title:"退单原因不能为空",
			        icon: 'none',
			        duration: 2000
			      });
			      return false
			    }
			    let params = {
			        oid:this.tdorder,
					memo:this.memo.replace(/\s*/g,"")
			    }
			
			    let _this = this
			    Api.revokeOrder(params).then(res=>{
			      if(res.retCode == 0){
			        if(_this.tdstate==0){
			          uni.showToast({
			            title:"已同意退单",
			            icon: 'success',
			            duration: 2000,
			            complete: () => {
			              setTimeout(
			                ()=> {
			                  _this.goodsData=[]
							  _this.pageNum = 0
							  _this.moreData=false
							  _this.nodata=false
							  _this.showkw=false
			                  _this.queryOrderBystate()
			                },
			                2000
			              )
			            }
			          });
			        }else{
			          uni.showToast({
			            title:"退单申请提交成功，请前往退单页查看审核结果！",
			            icon: 'none',
			            duration: 2000,
			            complete: () => {
			              setTimeout(
			                ()=> {
								_this.goodsData=[]
								_this.pagenum=-1
								_this.moreData=false
								_this.nodata=false
								_this.showkw=false
			                  _this.queryOrderBystate()
			                },
			                2000
			              )
			            }
			          });
			        }
			      }else{
			        uni.showToast({
			          title: res.info,
			          icon: 'none',
			          duration: 2000
			        });
			      }
			    })
			  },
			  waitPjo(){
				// this.pagenum=-1
				if(this.moreData){
				  return false
				}else{
				  this.pageNum++
				}
				console.log("this.pageNum",this.pageNum)
				uni.showLoading({
				  title: '加载中...',
				})
				let userId = uni.getStorageSync('userId')
				let params = {
				  userId:userId,
				  deptId:this.rcode,
				  ostate:2,
				  pageNum:this.pageNum,
				  pageSize:this.pageSize
				}
				let _this = this
				dpjOrder(params).catch(res=>{
				    if(res.data.rows.length > 0){
						const newList = res.data.rows
						const total = res.data.total
						if(_this.goodsData.length < total){
						  _this.goodsData=[..._this.goodsData,...newList]
						}else{
						  _this.moreData=true
						}
				    }else{
						if(_this.pageNum==1){
						  _this.nodata=true
						 }
						 _this.moreData=true
				    }
					uni.hideLoading()
				})
			  },
			  onChange(event) {
				if(event){
					this.active = event.index
				}
				this.goodsData=[]
				this.pageNum=0
				this.moreData=false
				this.nodata=false
				this.showkw=false
			    if(this.active==0){
			      this.state=""
			      this.queryOrderBystate()
			    }else if(this.active==1){
					this.state=2
			        this.waitPjo()
			      // this.waitOrder()
			    }else if(this.active==2){
			      this.state=3
			      this.queryOrderBystate()
			    }else{
			      // this.queryBackorder()
			    }
			}
		}
	}
</script>
	
<style>
	.cont{background-color: #F5F5F5;}
	.hjsf{display:flex;border-top:1px solid #F5F5F5;border-bottom:1px solid #F5F5F5;padding:10rpx auto}
	.gsorder{flex:2;}
	.search-input {
	  color: #999;
	  padding: 20rpx;
	  background: #f1f1f2;
	  display: flex;
	}
    .uni-list-cell{display:flex;justify-items: center;justify-content: space-between;margin:10px 0px}
	 .search-input .search-icon {
	    margin-right: 8rpx;
	  }
	.gsorder image{width:5rem;height:5rem;object-fit:cover}
	.qrqc{display:flex;justify-items: center;align-items: center;}
	.qcbtn{width:100rpx!important;height:40rpx!important;}
	.item{color:#F66B71;font-size:1.2rem}
	.orderstate{color:#F66B71;}
	.orderwarp{width:100%;height:100rpx;position:fixed;z-index:999;background: #FFFFFF;}
</style>
